<template>
  <view class="flex-col">
    <navbar title="意见反馈"></navbar>
    <view class="block white">
      <view class="sub-title">请描述场景中的问题</view>
      <view class="flex-row" style="flex-wrap: wrap;">
        <view class="flex-row" v-for="(item,i) in list" :key="i" style="width: 50%;margin-bottom: 44upx">
          <radio :checked="item.id == index" @click="index=item.id" color="#3073F6"
                 style="transform:scale(0.7);margin-left: 20%"/>
          <text>{{ item.title }}</text>
        </view>
      </view>
    </view>
    <view class="block">
      <view class="sub-title">问题和意见</view>
      <view class="flex-col" style="height: 288upx;background-color: #fff;padding: 30upx">
        <textarea class="input-opinion" maxlength="200" placeholder="请填写您的问题表述以便我们提供更好的帮助"
                  placeholder-style="color:#CCCCCC" v-model="opinion"/>
        <text class="option-length-text">{{ opinion.length + '/200' }}</text>
      </view>
    </view>
    <view class="block">
      <view class="sub-title">选择图片</view>
      <view class="flex-row">
      </view>
      <view class="flex-row" style="flex-wrap: wrap">
        <image v-for="(item,i) in photo" :src="item.img"
               mode="aspectFill"
               style="width: 184upx;height: 184upx;margin-left: 30upx;margin-bottom: 10upx;border-radius: 10upx"
               :key="i"></image>
        <image src="/static/tianjiatupian@3x.png" v-if="photo.length<9"
               style="width: 184upx;height: 184upx;margin-left: 30upx"
               @click="addImgAction"></image>
      </view>
    </view>
    <view class="block">
      <view class="sub-title">请留下您常用的联系方式</view>
      <view class="flex-col" style="height: 40upx;background-color: #fff;padding: 30upx">
        <input class="input-opinion" placeholder="输入手机号以便我们联系您" placeholder-style="color:#CCCCCC"
               v-model="phone"/>
      </view>
    </view>
    <view class="custom-btn primary submit" @click="submit">确定</view>
  </view>
</template>

<script>
import Navbar from "../../components/navbar";
import {commonApi} from '@/api'
import {errorCorrectionApi} from "../../api";

export default {
  components: {Navbar},
  data() {
    return {
      questionId: null,
      index: 1,
      opinion: '',//意见
      phone: '',
      photo: [],//图片
      permission: false,
      list: [
        {
          id: 1,
          title: '题目错误'
        },
        {
          id: 2,
          title: '图片无显示'
        },
        {
          id: 3,
          title: '解释错误'
        },
        {
          id: 4,
          title: '其他问题'
        },

      ]
    }
  },

  onLoad({id}) {
    this.questionId = id
  },

  methods: {
    async submit() {
      if (!this.opinion || this.opinion.length === 0) {
        uni.showToast({
          title: '请输入问题和意见',
          duration: 2000,
          icon: 'none'
        });
        return
      }

      if (this.photo && this.photo.length > 0) {
        await this.uploadImages(this.questionId, this.index, this.opinion, this.phone, this.photo)
      } else {
        await this.uploadData(this.questionId, this.index, this.opinion, this.phone, this.photo)
      }
    },
    async uploadImages(questionId, index, opinion, phone, photo) {
      uni.showLoading({
        title: '加载中...',
      })
      const res = await commonApi.getUploadToken()
      const {
        token,
        imgHost,
        url
      } = res.data.data
      const images = [];
      for (let i = 0; i < photo.length; i++) {
        const filePath = photo[i].img;
        const key = Math.random().toString(36).substr(2); //生成一个随机字符串的文件名

        uni.uploadFile({
          url, //华东地区上传地址
          filePath,
          name: 'file',
          formData: {
            token, //刚刚获取的上传凭证
            'key': 'error_report/' + key //这里是为文件设置上传后的文件名
          },
          success: async (uploadFileRes) => {
            console.log(uploadFileRes.data)
            const data = JSON.parse(uploadFileRes.data.trim())
            const img = imgHost + '/' + data.key
            // console.log('---------------' + img)
            images.push({img});
            if (images.length === photo.length) {
              await this.uploadData(questionId, index, opinion, phone, images)
            }
          },
          fail: (e) => {
            console.log('hsf', 'uploadFile===error:' + JSON.stringify(e));
          }
        })
      }
    },
    async uploadData(questionId, index, opinion, phone, photo) {
      uni.showLoading({
        title: '加载中...',
      })
      try {
        await errorCorrectionApi.create(questionId, index, opinion, phone, photo)
        uni.showToast({
          title: '提交成功，感谢您的反馈！',
          icon: 'success',
          duration: 2000
        });
        uni.navigateBack()
      } catch (e) {
        uni.showToast({
          title: e.data.msg,
          icon: 'none',
          duration: 2000
        });
      }
      uni.hideLoading()
    },
    tryUpdateAvatar() {
      uni.showModal({
        title: "温馨提示",
        content: "将申请相机、相册读取权限用于上传意见反馈图片",
        success: (res) => {
          if (res.confirm) {
            this.addImgAction()
          }
        }
      })
    },
    addImgAction() {
      const request = () => {
        const count = 9 - this.photo.length
        uni.chooseImage({
          count: count,
          sizeType: 'compressed',
          success: async (result) => {
            for (let i = 0; i < result.tempFilePaths.length; i++) {
              const img = result.tempFilePaths[i];
              this.photo.push({img});
            }
          }
        })
      }

      if (!this.permission) {
        uni.showModal({
          title: "温馨提示",
          content: "将申请相机、相册读取权限用于上传意见反馈图片",
          success: (res) => {
            if (res.confirm) {
              this.permission = true
              request()
            }
          }
        })
      } else {
        request()
      }
    },
  }

}
</script>

<style lang="scss">
page {
  background-color: #f7f7f7;
}

.block {
  padding-top: 40upx;

  &.white {
    background-color: #fff;
  }
}

.sub-title {
  font-size: 30upx;
  color: #000000;
  font-weight: bold;
  margin-left: 30upx;
  margin-bottom: 30upx
}

.input-opinion {
  font-size: 28upx;
  width: 100%;
  flex: 1;

}

.option-length-text {
  color: #CCCCCC;
  font-size: 30upx;
  align-self: end;
}

.submit {
  margin: 50upx 94upx;
}

</style>
